<template>
  <div>
    <!-- 顶部navbar -->
    <van-nav-bar
      title="城市列表"
      left-arrow
      @click-left="$router.back()"
      :fixed="true"
      :z-index="2"
    />
    <!-- 索引栏 -->
    <div class="bottom">
      <van-index-bar :index-list="indexList" highlight-color="#20b97a">
        <div v-for="(item, key) in allObj" :key="key">
          <van-index-anchor :index="key">
            <span style="font-size: 16px" v-if="key === '#'">当前城市</span>
            <span style="font-size: 16px" v-else-if="key === '热'"
              >热门城市</span
            >
            <span style="font-size: 16px" v-else>{{ key }}</span>
          </van-index-anchor>
          <van-cell
            v-for="(item1, index) in item"
            :key="index"
            :title="item1.label"
            @click="onClick(item1)"
          />
        </div>
      </van-index-bar>
    </div>
  </div>
</template>

<script>
import { getCitys, getHotCitys } from '@/api/city'
export default {
  name: 'city-page',
  components: {},
  props: {},
  data() {
    return {
      indexList: [],
      allObj: {}
    }
  },
  computed: {},
  watch: {},
  async created() {
    const res1 = await getCitys({ level: 1 })
    const res2 = await getHotCitys()
    // console.log(res1)
    // console.log(res2)
    const allObj = {
      '#': [
        JSON.parse(window.localStorage.getItem('city')) || {
          label: '上海',
          value: 'AREA|dbf46d32-7e76-1196',
          pinyin: 'shanghai',
          short: 'sh'
        }
      ],
      热: res2.body,
      A: [],
      B: [],
      C: [],
      D: [],
      E: [],
      F: [],
      G: [],
      H: [],
      I: [],
      J: [],
      K: [],
      L: [],
      M: [],
      N: [],
      O: [],
      P: [],
      Q: [],
      R: [],
      S: [],
      T: [],
      U: [],
      V: [],
      W: [],
      X: [],
      Y: [],
      Z: []
    }
    res1.body.forEach((item) => {
      const k = item.short[0].toUpperCase()
      allObj[k].push(item)
    })
    // console.log(allObj)
    // 遍历allObj,把所有的值是空数组的这一项属性移除掉
    for (const k in allObj) {
      if (!allObj[k].length) {
        delete allObj[k]
      }
    }
    this.indexList = Object.keys(allObj)
    this.allObj = allObj
  },
  methods: {
    onClick(city) {
      localStorage.setItem('city', JSON.stringify(city))
      this.$router.push('/home')
    }
  }
}
</script>

<style scoped lang="less">
.bottom {
  position: fixed;
  top: 46px;
  bottom: 0;
  left: 0;
  right: 0;
  overflow: auto;
}
::v-deep .van-index-bar__sidebar {
  margin-top: 15px;
}
::v-deep .van-index-bar__index {
  margin: 6px 0;
  font-size: 14px;
}
</style>
